package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private Map<String , String> headers = new HashMap<>();
    private String method;
    private String uri;
    private String protocol;

    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析消息正文
        parseContent();
    }




    private String readLine() throws IOException {

        InputStream in = socket.getInputStream();//创建输入流读取请求数据

        StringBuilder builder = new StringBuilder();
        int d;
        char pre = 'a', cur = 'a';//用两个字符变量，分别代表当前字符和上一个字符
        while ((d = in.read())!=-1){
            pre = (char)d;//将读取到的字节转换为字符赋值给pre
            if (cur==13&&pre==10){//当上一个字符等于回车，当前字符等于换行时，循环结束
                break;
            }
            builder.append(pre);//将读取的字符拼接到builder中
            cur = pre;//在进行下一次读取前将当前字符赋值给cur，让cur作为上一次读取的字符
        }
        return builder.toString().trim();//转换为字符串类型并去两边的空字符
    }

    private void parseRequestLine() throws IOException {
        String line =readLine();

        String[] array = line.split("\\s");
        //将解析行的内容拆分成三部分，分别赋值给三个变量
        method = array[0];
        uri = array[1];
        protocol = array[2];

        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    private void parseHeaders() throws IOException {
        String line;
        while (!(line = readLine()).isEmpty()){
            String[] array = line.split(":\\s");
            headers.put(array[0],array[1]);
            System.out.println(line);
        }
        System.out.println(headers);
    }

    private void parseContent(){

    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }
}
